<script setup>

import {inject, onMounted, ref, toRefs, watch} from "vue";
// import {useRoute} from "vue-router";
import {buyFromCartService, removeItemFromCart, showCart} from "@/api/cartOrder";
import router from "@/router";

var username = localStorage.getItem("username");
const data=ref([]);

let cartData;
const isSearch = inject('isSearch')
isSearch.value=false;

 const getCart=async()=>{
       cartData=await showCart();
     if(cartData.status==1){
       data.value=cartData.data;
       console.log(cartData.data);
       console.log('json '+JSON.stringify(cartData.data))

     }else {
       //未登录
       console.log(cartData.status);
     }
     console.log('username='+username)
      await getTotal();
 }


const subtotal = ref(0);

const Itemtotal = (CartItem) => {
  return CartItem.item.listprice * CartItem.cartItem.quantity;
}

const getTotal=async ()=>{
  console.log('data.value='+data.value)

  let sum = 0;
  // 使用 toRefs 将 data 转换为 ref 对象
  const refs = toRefs(data.value);
  // 遍历 ref 对象，并将值添加到数组中
  const dataArray = Object.values(refs).map(ref => ref.value);
  // 遍历数组，计算总和
  dataArray.forEach(CartItem => {
    sum += Itemtotal(CartItem);
  });
  subtotal.value = sum;
}
getCart();
// 在组件渲染后，更新总价
onMounted(() => {
  getTotal();
  console.log('onMounted')
});

const remove=async (itemId)=>{
  console.log('itemid='+itemId)
  let result=await removeItemFromCart(itemId);
  if(result.status===1){
    console.log('remove success')
    await getCart();
  } else {
    alert('删除失败');
  }
}

const buyNowFormCart=async()=>{

     let result= await buyFromCartService();
     if(result.status===1){
       console.log('12345')
       console.log(result.data);
       await router.push({
         path: '/confirmOrder',
         query: {
           orderId:result.data.orderId
         }
       });
     }else{
       alert('购买失败');
     }
}

// 监听购物车数据的变化，更新总价
// watch(data, () => {
//   getTotal();
//   console.log('watch')
// });
// watch(() => data.value.map(item => item.qty), () => {
//   getTotal();
// });
watch(data, () => {
  getTotal();
}, { deep: true });
</script>
<template>
  <div id="show">
    <div id="Cart">
      <div id="petName"> Shopping Cart </div>
      <div id="cartContent">
<!--        <form >-->
          <table class="shoppingCartTable">
            <tr>
              <th>CartItem.itemid</th>
              <th><b>Product ID</b></th>
              <th><b>Description</b></th>
              <th><b>In Stock?</b></th>
              <th><b>Quantity</b></th>
              <th><b>List Price</b></th>
              <th><b>Total Cost</b></th>
              <th>operation</th>
            </tr>
            <tbody>
<!--            <tr v-if="data.value.length===0">-->
<!--              <td colspan="8"><b>Your order information is empty.</b></td>-->
<!--            </tr>-->
            <tr  v-for="CartItem in data" :key="CartItem.cartItem.itemid" >
              <td>
                <a>
                  <span >{{ CartItem.cartItem.itemid }}</span>
                </a>
              </td>
              <td>{{ CartItem.item.productid }}</td>
              <td>
                <span >{{ CartItem.item.attr1 }}</span>
              </td>
              <td>{{ CartItem.item.isup}}</td>
              <!--                    <td th:text="${cartItem.inStock}">cartItem.inStock</td>-->
              <td>
                <input type="text" class="quantity" v-model="CartItem.cartItem.quantity">
              </td>
              <!--                    <td th:text="${#numbers.formatDecimal(cartItem.item.listPrice, 0, 'POINT', 2, 'COMMA', 'en_US')}"></td>-->
              <td>{{ CartItem.item.listprice }}</td>

              <td>
                <label ref="total" class="total">{{Itemtotal(CartItem)}}</label>
              </td>
              <td>
                <button @click="remove(CartItem.cartItem.itemid)">Remove</button>
              </td>
            </tr>

            <tr >
              <td colspan="7" class="updateCart">
                Sub Total:
                <label id="subtotalref" >{{ subtotal}}
                </label>
              </td>
              <td class="updateCart">
              <button @click="buyNowFormCart()">Buy Now</button>
              </td>
            </tr>
            </tbody>
          </table>
<!--        </form>-->
      </div>
    </div>
    <div id="Separator">&nbsp;</div>
  </div>
</template>

<style>
.shoppingCartTable{
  border-collapse: collapse;
  margin-left: 10%;
  width: 80%;
  text-align: center;
}

.shoppingCartTable th{
  color: #fff;
  background-color: #35813b;
  border-bottom: 2px solid #37833d;
  border-right: 1px solid #c1efca;
  border-top: 1px solid #97d690;
  text-align: center;
  text-shadow: -1px -1px 1px #666666;
  padding: 3px;
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}
.shoppingCartTable td{
  color: black;
  font-size: 15px;
  text-shadow: 1px 1px 1px #ffffff;
  padding: 3px;
  margin: 0 0px;
  border: 1px solid lightgray;
  font-weight: bold;
}


.shoppingCartTable tbody{
  background: #eeeeee;
}
.shoppingCartTable td:last-child{
  text-align: center;
}
.shoppingCartTable tbody tr:last-child {
  text-align: right;
  font-size: 20px;
  color: green;
  font-weight: lighter;
  padding: 3px;
  border: 1px solid lightgray;
  border-top: 2px solid green;
  background-color: #c1efca;
}

</style>